import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Booking } from '../booking/entities/booking.entity';
import { Repository } from 'typeorm';

@Injectable()
export class StatisticService {
  @InjectRepository(Booking)
  private bookingRepository: Repository<Booking>;

  async userBookingCount(startTime: string, endTime: string) {
    const res = await this.bookingRepository
      .createQueryBuilder('b')
      .select('u.id', '用户id')
      .addSelect('u.username', '用户名')
      .leftJoin('b.user', 'u')
      .addSelect('count(1)', '预订次数')
      .where('b.startTime between :time1 and :time2', {
        time1: startTime,
        time2: endTime,
      })
      .groupBy('b.user')
      .getRawMany();
    return res;
  }

  async roomBookingCount(startTime: string, endTime: string) {
    const res = await this.bookingRepository
      .createQueryBuilder('b')
      .select('m.id', 'meetingRoomId')
      .addSelect('m.name', 'meetingRoomName')
      .leftJoin('b.room', 'm')
      .addSelect('count(1)', '预订次数')
      .where('b.startTime between :time1 and :time2', {
        time1: startTime,
        time2: endTime,
      })
      .groupBy('b.room')
      .getRawMany();
    return res;
  }
}
